/**
 * Created by LC on 2019/11/16
 */
package com.hw.paltfrom.service.casemain;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.github.pagehelper.PageInfo;
import com.hw.paltfrom.controller.system.BaseFrontController;
import com.hw.paltfrom.exception.HWSystemException;
import com.hw.paltfrom.mapper.HwBaseAnnexesfileMapper;
import com.hw.paltfrom.mapper.HwCaseMainMapper;
import com.hw.paltfrom.mapper.HwCaseSrccomMapper;
import com.hw.paltfrom.pojo.*;
import com.hw.paltfrom.rescode.HWSystemCode;
import com.hw.paltfrom.service.doncutor.BaseWorkflowService;
import com.hw.paltfrom.service.doncutor.CommandWorkflowService;
import com.hw.paltfrom.utils.ExcelFormatUtil;
import com.hw.paltfrom.utils.RandomNumberUtil;
import com.hw.paltfrom.utils.ResponeResultUtil;
import com.hw.paltfrom.vo.FileInfo;
import com.hw.paltfrom.vo.SourceVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 源头企业倒查
 */
@Service
public class SourceEnterpriseService {

    @Autowired
    HwCaseMainMapper caseMainMapper;

    @Autowired
    HwCaseSrccomMapper caseSrccomMapper;

    @Autowired
    HwBaseAnnexesfileMapper baseAnnexesfileMapper;

    @Autowired
    CommandWorkflowService commandWorkflowService;

    @Autowired
    BaseWorkflowService baseWorkflowService;
    /**
     * 查询
     * @param vo
     * @return
     */
    public Map<String,Object> queryList(SourceVo vo){
        //取出源头企业名称条件
        String sourceDepName = vo.getfTosrccomname();
        //根据所传参数,进行条件查询
        Wrapper<HwCaseMain> caseMainWrapper = new EntityWrapper<>();
        caseMainWrapper.eq("F_AJ_CrtStep","04")
                .eq(vo.getIsDealed() == 0,"F_AJ_Investigate",0)
                .ne(vo.getIsDealed() != 0,"F_AJ_Investigate",0)
                .eq(StringUtils.isNotBlank(vo.getFareacode()),"F_AreaCode",vo.getFareacode())
                .like(StringUtils.isNotBlank(vo.getfClTruckno()),"F_CL_TruckNo",vo.getfClTruckno())
                .like(StringUtils.isNotBlank(vo.getfSrcname()),"F_SrcName",vo.getfSrcname())
                .eq(StringUtils.isNotBlank(vo.getfClAxis()),"F_CL_Axis",vo.getfClAxis())
                .eq(vo.getfClOverweight() != null,"F_CL_OverWeight",vo.getfClOverweight())
                .between((vo.getStartTime() != null && vo.getEndTime() != null),"F_CL_CheckTime",vo.getStartTime(),vo.getEndTime()).orderBy("F_CL_CheckTime",false);
        //创建分页条件
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        List<HwCaseMain> hwCaseMainList = caseMainMapper.selectList(caseMainWrapper);
        if (hwCaseMainList.size() <= 0){
            return ResponeResultUtil.fail(HWSystemCode.DATA_NOTFOUND);
        }
        //源头企业倒查信息表
//        List<CaseMainAndSource> caseMainAndSourceList = new LinkedList<>();
//        for (HwCaseMain hwCaseMain : hwCaseMainList) {
//            CaseMainAndSource c = new CaseMainAndSource();
//            c.setCaseMain(hwCaseMain);
//            String caseid = hwCaseMain.getfCaseid();
//            Wrapper<HwCaseSrccom> wrapper = new EntityWrapper<>();
//            wrapper.eq("F_MainId",caseid);
//            List<HwCaseSrccom> hwCaseSrccoms = caseSrccomMapper.selectList(wrapper);
//            HwCaseSrccom hwCaseSrccom = null;
//            if (hwCaseSrccoms.size() != 0){
//                hwCaseSrccom = hwCaseSrccoms.get(0);
//                String tosrccomname = hwCaseSrccom.getfTosrccomname();
//                c.setCaseSrccom(hwCaseSrccom);
//            }
//            caseMainAndSourceList.add(c);
//        }
        PageInfo<HwCaseMain> info = new PageInfo<>(hwCaseMainList);

        return ResponeResultUtil.successNotice(HWSystemCode.SUCCESS,info);
    }

    /**
     * 办理
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class, HWSystemException.class})
    public Map<String,Object> dealtask(SourceVo vo){
        //取出执法id
        String caseid = vo.getfCaseid();
        //取出源头企业信息id
        Wrapper<HwCaseSrccom> wrapper = new EntityWrapper<>();
        wrapper.eq("F_MainId",caseid);
        List<HwCaseSrccom> hwCaseSrccoms = caseSrccomMapper.selectList(wrapper);
        if (hwCaseSrccoms.size() == 0){
            return ResponeResultUtil.fail(HWSystemCode.PARAMS_ERROR);
        }
        String srccomid = hwCaseSrccoms.get(0).getfSrccomid();
        //创建源头企业信息模板对象
        HwCaseSrccom hwCaseSrccom = new HwCaseSrccom();
        //查出当前执法信息表
        HwCaseMain caseMain_old = caseMainMapper.selectById(caseid);
        //判断是否办理
        Integer fAjInvestigate = caseMain_old.getfAjInvestigate();
        if (fAjInvestigate != 0){
            return ResponeResultUtil.failNotice(HWSystemCode.FAIL,"已经办理过了");
        }
        //操作人选择处罚阶段
        Integer isPunished = vo.getfAjInvestigate();
        String folderId = "";
        if (isPunished == 1){
            //插入附件
            String remarkFolderId = RandomNumberUtil.getNumber();
            List<FileInfo> sourceBackList = vo.getSourceBackList();
            int i =0;
            for (FileInfo fileInfo : sourceBackList) {
                ++i;
                HwBaseAnnexesfile hwBaseAnnexesfile = new HwBaseAnnexesfile();
                hwBaseAnnexesfile.setFileId(RandomNumberUtil.getNumber());
                hwBaseAnnexesfile.setfFolderid(remarkFolderId);
                hwBaseAnnexesfile.setFileType(fileInfo.getFileType());
                hwBaseAnnexesfile.setFileName("源头倒查情况说明附件"+String.valueOf(i));
                hwBaseAnnexesfile.setFilePath(fileInfo.getFilePath());
                hwBaseAnnexesfile.setFileSize(fileInfo.getFileSize());
                hwBaseAnnexesfile.setFileMoudletype("源头倒查情况说明File");
                hwBaseAnnexesfile.setfCreatedate(new Timestamp(System.currentTimeMillis()));
                hwBaseAnnexesfile.setfCreateusername(vo.getfAccount());
                Integer insert = baseAnnexesfileMapper.insert(hwBaseAnnexesfile);
                if (insert != 1) {
                    throw new HWSystemException();
                }
            }
            folderId = remarkFolderId;
            //插入源头企业倒查表
            hwCaseSrccom.setfSrccomid(srccomid);
            hwCaseSrccom.setfTosrccomname(vo.getfTosrccomname());
            hwCaseSrccom.setfRemarkfile(remarkFolderId);
            hwCaseSrccom.setfOpertime(vo.getfOpertime());
            hwCaseSrccom.setfOperuser(vo.getfOperuser());
            hwCaseSrccom.setfOperuserphone(vo.getfOperuserphone());
            hwCaseSrccom.setfRemark(vo.getfRemark());
            hwCaseSrccom.setfOperuserid(vo.getfAccount());
            hwCaseSrccom.setfOperusername(vo.getfRealName());
            hwCaseSrccom.setfOpsertime(new Date());
            Integer update = caseSrccomMapper.updateById(hwCaseSrccom);
            if (update !=1){
                throw new HWSystemException();
            }
        }else if (isPunished == 2){
            //插入附件
            String goodsFolderId = RandomNumberUtil.getNumber();
            String punishFolderId = RandomNumberUtil.getNumber();
            List<FileInfo> goodsList = vo.getGoodsList();
            int i = 0;
            for (FileInfo fileInfo : goodsList) {
                ++i;
                HwBaseAnnexesfile hwBaseAnnexesfile = new HwBaseAnnexesfile();
                hwBaseAnnexesfile.setFileId(RandomNumberUtil.getNumber());
                hwBaseAnnexesfile.setfFolderid(goodsFolderId);
                hwBaseAnnexesfile.setFileType(fileInfo.getFileType());
                hwBaseAnnexesfile.setFileName("货运单附件"+String.valueOf(i));
                hwBaseAnnexesfile.setFilePath(fileInfo.getFilePath());
                hwBaseAnnexesfile.setFileSize(fileInfo.getFileSize());
                hwBaseAnnexesfile.setFileMoudletype("货运单");
                hwBaseAnnexesfile.setfCreatedate(new Timestamp(System.currentTimeMillis()));
                hwBaseAnnexesfile.setfCreateuserid(vo.getfAccount());
                hwBaseAnnexesfile.setfCreateusername(vo.getfRealName());
                Integer insert = baseAnnexesfileMapper.insert(hwBaseAnnexesfile);
                if (insert != 1) {
                    throw new HWSystemException();
                }
            }
            List<FileInfo> sourcePunishList = vo.getSourcePunishList();
            int j = 0;
            for (FileInfo fileInfo : sourcePunishList) {
                ++j;
                HwBaseAnnexesfile hwBaseAnnexesfile = new HwBaseAnnexesfile();
                hwBaseAnnexesfile.setFileId(RandomNumberUtil.getNumber());
                hwBaseAnnexesfile.setfFolderid(punishFolderId);
                hwBaseAnnexesfile.setFileType(fileInfo.getFileType());
//				hwBaseAnnexesfile.setFileName(vo.getFileName()+String.valueOf(i));
                hwBaseAnnexesfile.setFileName("源头处罚决定书附件"+String.valueOf(j));
                hwBaseAnnexesfile.setFilePath(fileInfo.getFilePath());
                hwBaseAnnexesfile.setFileSize(fileInfo.getFileSize());
                hwBaseAnnexesfile.setFileMoudletype("源头处罚决定书");
                hwBaseAnnexesfile.setfCreatedate(new Timestamp(System.currentTimeMillis()));
                hwBaseAnnexesfile.setfCreateuserid(vo.getfAccount());
                hwBaseAnnexesfile.setfCreateusername(vo.getfRealName());
                Integer insert = baseAnnexesfileMapper.insert(hwBaseAnnexesfile);
                if (insert != 1) {
                    throw new HWSystemException();
                }
            }
            //插入源头企业倒查表
            folderId = goodsFolderId +","+ punishFolderId;
            hwCaseSrccom.setfSrccomid(srccomid);
            hwCaseSrccom.setfTosrccomname(vo.getfTosrccomname());
            hwCaseSrccom.setfSrcamount(vo.getfSrcamount());
            hwCaseSrccom.setfOpertime(vo.getfOpertime());
            hwCaseSrccom.setfOperuser(vo.getfOperuser());
            hwCaseSrccom.setfOperuserphone(vo.getfOperuserphone());
            hwCaseSrccom.setfRemark(vo.getfRemark());
            hwCaseSrccom.setfSrcgoodsannex(goodsFolderId);
            hwCaseSrccom.setfSrcpunishannex(punishFolderId);
            hwCaseSrccom.setfOperuserid(vo.getfAccount());
            hwCaseSrccom.setfOperusername(vo.getfRealName());
            hwCaseSrccom.setfOpsertime(new Date());
            Integer update = caseSrccomMapper.updateById(hwCaseSrccom);
            if (update !=1){
                throw new HWSystemException();
            }
        }
        caseMain_old.setfAjInvestigate(isPunished);
        Integer caseMainUpdate = caseMainMapper.updateById(caseMain_old);
        if (caseMainUpdate != 1){
            throw new HWSystemException();
        }

        //查询工作流
        HwBaseWorkflow presentWorkflow = baseWorkflowService.getPresentWorkflow(caseMain_old.getfAjCrtstep(), caseMain_old.getFlowCode());
        // 审批流水数据
        HwCommandWorkflow hwCommandWorkflow = new HwCommandWorkflow();


        hwCommandWorkflow.setCommandworkflowId(RandomNumberUtil.getNumber());//主键
        hwCommandWorkflow.setWorkflowModule("02");
        hwCommandWorkflow.setWorkflowType(caseMain_old.getFlowCode());
        hwCommandWorkflow.setWorkflowCode(caseMain_old.getfAjCrtstep());
        hwCommandWorkflow.setWorkflowCodename(presentWorkflow.getWorkflowCodename());
        hwCommandWorkflow.setCommandworkflowButtonname("源头责任倒查办理");
        hwCommandWorkflow.setfAccount(vo.getfAccount());
        hwCommandWorkflow.setfFromdepcode(vo.getfFromdepcode());
        hwCommandWorkflow.setfFromdepname(vo.getfFromdepname());
        hwCommandWorkflow.setCommandworkflowDatatime(new Date());
        hwCommandWorkflow.setCommandworkflowContent(vo.getfRemark());
        hwCommandWorkflow.setWorkflowNextcode("99");
        hwCommandWorkflow.setWorkflowNextcodename("");
        hwCommandWorkflow.setObjectId(caseid);
        hwCommandWorkflow.setfAnnexes(folderId);

        boolean b = commandWorkflowService.addWorkflow(hwCommandWorkflow);
        if (!b) {
            throw new HWSystemException();
        }
        return ResponeResultUtil.success(HWSystemCode.SUCCESS);
    }

    //查询2
    public Map<String, Object> queryListByCounty(SourceVo vo) {
        //取出源头企业名称条件
        String sourceDepName = vo.getfTosrccomname();
        //根据所传参数,进行条件查询
        Wrapper<HwCaseMain> caseMainWrapper = new EntityWrapper<>();
        String[] inSteps = {"04","05","06","07"};
        caseMainWrapper.in("F_AJ_CrtStep",inSteps)
                .eq(StringUtils.isNotBlank(vo.getFareacode()),"F_AreaCode",vo.getFareacode())
                .eq(vo.getfSrcamount() != null,"F_AJ_PoliceAmount",vo.getfSrcamount())
                .eq(vo.getfAjInvestigate() !=null,"F_AJ_Investigate",vo.getfAjInvestigate())
                .like(StringUtils.isNotBlank(vo.getfClTruckno()),"F_CL_TruckNo",vo.getfClTruckno())
                .like(StringUtils.isNotBlank(vo.getfSrcname()),"F_SrcName",vo.getfSrcname())
                .eq(StringUtils.isNotBlank(vo.getfClAxis()),"F_CL_Axis",vo.getfClAxis())
                .eq(vo.getfClOverweight() != null,"F_CL_OverWeight",vo.getfClOverweight())
                .between((vo.getStartTime() != null && vo.getEndTime() != null),"F_CL_CheckTime",vo.getStartTime(),vo.getEndTime()).orderBy("F_CL_CheckTime",false);
        //创建分页条件
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        List<HwCaseMain> hwCaseMainList = caseMainMapper.selectList(caseMainWrapper);
        if (hwCaseMainList.size() <= 0){
            return ResponeResultUtil.fail(HWSystemCode.DATA_NOTFOUND);
        }
        Pagination pagination = PageHelper.getPagination();
        PageInfo<HwCaseMain> info = new PageInfo<>(hwCaseMainList);

        return ResponeResultUtil.successNotice(HWSystemCode.SUCCESS,info);
    }

    //导出
    public ResponseEntity<byte[]> queryExport(SourceVo vo) {
        //根据所传参数,进行条件查询
        Wrapper<HwCaseMain> caseMainWrapper = new EntityWrapper<>();
        String[] inSteps = {"04","05","06","07"};
        caseMainWrapper.in("F_AJ_CrtStep",inSteps);
        caseMainWrapper.eq(StringUtils.isNotBlank(vo.getFareacode()),"F_AreaCode",vo.getFareacode());
        caseMainWrapper.eq(vo.getfSrcamount() != null,"F_AJ_PoliceAmount",vo.getfSrcamount());
        caseMainWrapper.eq(vo.getfAjInvestigate() !=null,"F_AJ_Investigate",vo.getfAjInvestigate());
        caseMainWrapper.like(StringUtils.isNotBlank(vo.getfClTruckno()),"F_CL_TruckNo",vo.getfClTruckno());
        caseMainWrapper.like(StringUtils.isNotBlank(vo.getfSrcname()),"F_SrcName",vo.getfSrcname());
        caseMainWrapper.eq(StringUtils.isNotBlank(vo.getfClAxis()),"F_CL_Axis",vo.getfClAxis());
        caseMainWrapper.eq(vo.getfClOverweight() != null,"F_CL_OverWeight",vo.getfClOverweight());
        caseMainWrapper.between((vo.getStartTime() != null && vo.getEndTime() != null),"F_CL_CheckTime",vo.getStartTime(),vo.getEndTime()).orderBy("F_CL_CheckTime",false);
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());

        List<HwCaseMain> hwCaseMainList = caseMainMapper.selectList(caseMainWrapper);
        if(hwCaseMainList.size() == 0){
            return null;
        }
        InputStream export = this.export(hwCaseMainList);
        BaseFrontController baseFrontController = new BaseFrontController();
        try {
          return baseFrontController.buildResponseEntity(export,"源头责任倒查.xlsx");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private InputStream export(List<HwCaseMain> list) {

        ByteArrayOutputStream output = null;
        InputStream inputStream1 = null;
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
        CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式

        // 每一列字段名
        String[] strs = new String[] { "超限站","车牌号","轴数","静态称重(吨)","静态检测时间","超限吨数","源头企业","处罚金额(元)","处理时间","责任倒查"};

        // 字段名所在表格的宽度
        int[] ints = new int[] { 10000, 5000, 5000, 5000, 10000,5000,5000,5000,10000,5000};

        // 设置表头样式
        ExcelFormatUtil.initTitleEX(sheet, header, strs, ints);

        if (list != null && list.size() > 0) {

            DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentCellValue = "";
            for (int i = 0; i < list.size(); i++) {

                HwCaseMain caseMain = list.get(i);
                SXSSFRow row = sheet.createRow(i + 1);
                int j = 0;

                // 检测站
                SXSSFCell cell = row.createCell(j++);
                cell.setCellValue(caseMain.getfOverrunname());
                cell.setCellStyle(content);

                //车牌号
                cell = row.createCell(j++);
                cell.setCellValue(caseMain.getfClTruckno());
                cell.setCellStyle(content);

                //轴数
                cell = row.createCell(j++);
                cell.setCellValue(caseMain.getfClAxis());
                cell.setCellStyle(content);

                // 静态称重
                cell = row.createCell(j++);
                Double totalweight = caseMain.getfClTotalweight();
                if (totalweight == null){
                    totalweight = 0d;
                }
                double jtd=totalweight.doubleValue();
                cell.setCellValue(jtd);
                cell.setCellStyle(content);

                // 静态检测时间
                cell = row.createCell(j++);
                Date d = caseMain.getfClChecktime();
                if(d !=null){
                    currentCellValue = formater.format(d);
                    cell.setCellValue(currentCellValue);
                }else{
                    cell.setCellValue("");
                }
                cell.setCellStyle(content);

                // 超限吨数
                cell = row.createCell(j++);
                Double overweight = caseMain.getfClOverweight();
                if (overweight == null){
                    overweight = 0D;
                }
                double cxs=overweight.doubleValue();
                cell.setCellValue(cxs);
                cell.setCellStyle(content);

                //源头企业
                cell = row.createCell(j++);
                cell.setCellValue(caseMain.getfSrcname());
                cell.setCellStyle(content);

                //处罚金额(元)
                cell = row.createCell(j++);
                Integer fAjPoliceamount = caseMain.getfAjPoliceamount();
                if (fAjPoliceamount == null){
                    fAjPoliceamount = 0;
                }
                cell.setCellValue(fAjPoliceamount);
                cell.setCellStyle(content);

                //处理时间
                cell = row.createCell(j++);
                Date d1 = caseMain.getFAjCreatetime();
                if(d1!=null){
                    currentCellValue = formater.format(d1);
                    cell.setCellValue(currentCellValue);
                }else{
                    cell.setCellValue("");
                }

                //责任倒查
                cell = row.createCell(j++);
                cell.setCellValue(caseMain.getfAjInvestigate());
                cell.setCellStyle(content);
                cell.setCellStyle(content);
            }
        }
        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream1 = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                    if (inputStream1 != null)
                        inputStream1.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return inputStream1;
    }
}
